package com.shixihub.browservice.func;

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import reactor.core.publisher.Mono;

import java.util.Objects;

/**
 * @author LiShixi 2021/4/15 2:44 上午
 */
public class BrowServiceClient {
    private WebClient client = WebClient.create("http://127.0.0.1:8080");

    public String getResult() {

        return ">> result = " + client.get()
                .uri("/hello")
                .accept(MediaType.TEXT_PLAIN)
                .exchangeToMono(response -> {
                    if (response.statusCode().equals(HttpStatus.OK)) {
                        return response.bodyToMono(String.class);
                    } else if (response.statusCode().is4xxClientError()) {
                        return response.bodyToMono(Exception.class);
                    } else {
                        final Mono<WebClientResponseException> exception = response.createException();
                        return Mono.error(() -> Objects.requireNonNull(exception.block()).getCause());
                    }
                })
                .block();
    }
}
